﻿using CSRedis;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WorkOne.Domain;
using WorkOne.Domain.Model;

namespace WorkOne.Webapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly GoodsDbContext db;
        private readonly CSRedisClient redis;
        private readonly RedisClient redisClient;

        public OrderController(GoodsDbContext db, CSRedisClient redis, RedisClient redisClient)
        {
            this.db = db;
            this.redis = redis;
            this.redisClient = redisClient;
        }
    


        /// <summary>
        /// 订单添加
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        [HttpGet("AddOrder")]
        public IActionResult AddOrder(Order order)
        {
            #region

            return Ok(1);
            #endregion
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        [HttpGet("GetOrderDetail")]
        public IActionResult GetOrderDetail(int orderid)
        {
            #region

            var list = db.orders.Include(a => a.Address).Include(a => a.User).Where(s => s.OrderId == orderid).ToList();

            foreach (var item in list)
            {
                item.GoodsList = (from og in db.Set<OrderGoods>().ToList()
                                  join g in db.Set<Goods>().ToList()
                                  on og.GId equals g.Id
                                  where (og.OrderId == item.OrderId)
                                  select g).ToList();
                item.GoodsCount = 0;
                foreach (var item1 in item.GoodsList)
                {
                    item.GoodsCount += db.Set<OrderGoods>().First(a => a.GId == item1.Id && a.OrderId == item.OrderId).BuyCount;
                }
            }
            return Ok(list[0]);
            #endregion
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="ordercode"></param>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <param name="name"></param>
        /// <param name="state"></param>
        /// <param name="paytype"></param>
        /// <returns></returns>
        [HttpGet("OrderList")]
        public IActionResult OrderList(int pageIndex, int pageSize, string? ordercode, string?
            begintime = null, string? endtime = null, string? name = null, int state = 0, int paytype = 0)
        {
            #region

            int pageCount = 0;
            int totalCount = 0;

            var list = (from o in db.Set<Order>().ToList()
                        join og in db.Set<OrderGoods>().ToList()
                        on o.OrderId equals og.OrderId
                        join g in db.Set<Goods>().ToList()
                        on og.GId equals g.Id
                        where (string.IsNullOrEmpty(ordercode) || o.OrderCode.Contains(ordercode))
                        && (string.IsNullOrEmpty(begintime) || o.AddTime >= DateTime.Parse(begintime))
                        && (string.IsNullOrEmpty(endtime) || o.AddTime < DateTime.Parse(endtime).AddDays(1))
                        && (paytype == 0 || ((int)o.PayType) == paytype)
                        && (state == 0 || ((int)o.State) == state)
                        && (o.IsDel == false)
                        select o).Distinct();

            //if (days > 0 && days < 29)
            //{
            //    list = list.Where(a => a.CreateTime > DateTime.Now.AddDays(0 - days) && a.CreateTime < DateTime.Now.AddDays(0 - days+1)).ToList();
            //}
            //else if (days > 29)
            //{
            //    DateTime firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            //    list = list.Where(a => a.CreateTime > firstDayOfMonth && a.CreateTime < DateTime.Now).ToList();
            //}

            foreach (var item in list)
            {
                item.GoodsList = (from og in db.Set<OrderGoods>().ToList()
                                  join g in db.Set<Goods>().ToList()
                               on og.GId equals g.Id
                                  where (og.OrderId == item.OrderId)
                                  select g).ToList();
                item.GoodsCount = 0;
                foreach (var item1 in item.GoodsList)
                {
                    item.GoodsCount += db.Set<OrderGoods>().First(a => a.GId == item1.Id && a.OrderId == item.OrderId).BuyCount;
                }
            }

            totalCount = list.Count();
            pageCount = (int)Math.Ceiling(totalCount * 1.0 / pageSize);
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return Ok(new
            {
                totalCount = totalCount,
                pageCount = pageCount,
                list = list.ToList()
            });

            #endregion
        }

        /// <summary>
        /// 获取枚举订单状态
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetEnumOrderState")]
        public IActionResult GetEnumOrderState()
        {
            OrderState state = new OrderState();
            Dictionary<string, int> list = Enum.GetValues(typeof(OrderState))
            .Cast<OrderState>()
            .ToDictionary(enumVal => enumVal.ToString(), enumVal => (int)enumVal);
            var list2 = list.Select(a => new
            {
                label = a.Key,
                value = a.Value.ToString()
            });
            return Ok(list2);
        }

        /// <summary>
        /// 获取枚举支付类型
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetEnumPayType")]
        public IActionResult GetEnumPayType()
        {
            var a = typeof(Order);
            var b = Enum.GetValues<PayType>();
            List<object> list = new List<object>();
            foreach (var item in Enum.GetValues<PayType>())
            {
                list.Add(new
                {
                    name = item.ToString(),
                    value = item,
                });
            }
            return Ok(list);
        }


        /// <summary>
        /// 十二生肖+随机(高)
        /// </summary>
        /// <returns></returns>
        [HttpGet("action")]
        public async Task<IActionResult> action()
        {
            List<string> list = new List<string>();
            string[] strings = { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
            for (int i = 0; i < 6; i++)
            {
                Random random = new Random();
                int randomNumber = random.Next();
                int firstDigit = Math.Abs(randomNumber % 10);
                list.Add(strings[firstDigit]);
            }
            return Ok(list);
        }
        /// <summary>
        /// 高--测试(g)
        /// </summary>
        /// <returns></returns>
        [HttpGet("Ceshi")]
        public IActionResult Ceshi()
        {
            List<int> ints = new List<int>();
            for (int i = 0; i < 10; i++)
            {
                Random random = new Random();
                ints.Add(random.Next());
            }
            return Ok(ints);
        }
        /// <summary>
        /// 帅小伙
        /// </summary>
        /// <returns></returns>
        [HttpGet("ShuaiXiaoHuo")]
        public IActionResult ShuaiXiaoHuo()
        {
            var sb =new string[] {"帅","小","伙"};
            return Ok(sb);
        }
        /// <summary>
        /// 帅小伙2
        /// </summary>
        /// <returns></returns>
        [HttpGet("ShuaiXiaoHuo")]
        public IActionResult ShuaiXiaoHuo2()
        {
            var sb = new string[] { "帅", "小", "伙" ,"2"};
            return Ok(sb);
        }
    }
}